package com.hsh.persist;

import cn.hutool.core.util.StrUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.UUID;


public abstract class BaseController {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass().getSimpleName());


    @Autowired
    protected HttpServletRequest request;
    @Autowired
    protected HttpServletResponse response;


    public String getUuid() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    public String genFileName(MultipartFile file) {
        String fileOriginalName = file.getOriginalFilename();
        int index = fileOriginalName.lastIndexOf(".");
        String suffix = fileOriginalName.substring(index + 1);
        return getUuid() + "." + suffix;
    }

    /**
     * 文件下载
     *
     * @param file
     */
    protected void downloadFile(File file) {
        try (OutputStream out = response.getOutputStream();
             InputStream in = new FileInputStream(file)) {
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition",
                    "attachment; filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
            response.setContentLength((int) file.length());
            byte[] tempbytes = new byte[100];
            int byteread;
            while ((byteread = in.read(tempbytes)) != -1) {
                out.write(tempbytes, 0, byteread);
            }
            out.flush();
        } catch (IOException e) {
            logger.error("downloadFile()", e);
        }
    }

    protected void downloadFile2(String attachPath, String originalFileName) {
        File file = new File(attachPath);
        if (StrUtil.isEmpty(originalFileName)) {
            originalFileName = file.getName();
        }
        try (OutputStream out = response.getOutputStream();
             InputStream in = new FileInputStream(file)) {
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition",
                    "attachment; filename=" + URLEncoder.encode(originalFileName, "UTF-8"));
            response.setContentLength((int) file.length());
            byte[] tempbytes = new byte[100];
            int byteread;
            while ((byteread = in.read(tempbytes)) != -1) {
                out.write(tempbytes, 0, byteread);
            }
            out.flush();
        } catch (IOException e) {
            logger.error("downloadFile2():", e);
        }
    }

}
